package io2.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.util.Scanner;

public class NioClient {
    public static void main(String[] args) throws IOException {
        SocketChannel socketChannel = SocketChannel.open();
        socketChannel.configureBlocking(false);
        socketChannel.connect(new InetSocketAddress("127.0.0.1", 8080));
        while(!socketChannel.finishConnect()) {
            System.out.println("1");
        }
        System.out.println("已连接");
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入：");
        socketChannel.write(ByteBuffer.wrap(scanner.nextLine().getBytes()));
        System.out.println("数据发送完毕");
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        while(true) {
            if(socketChannel.read(buffer) > 0) {
                buffer.flip();
                byte[] bytes = new byte[buffer.remaining()];
                buffer.get(bytes);
                System.out.println("收到数据：" + new String(bytes));
                break;
            }
        }
        System.out.println("数据接收完毕， 数据来自：" + socketChannel.getRemoteAddress());
        socketChannel.close();
    }
}
